/*
 * 任务模块
 */

(function($) {
    //获取页面间的url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    var project_id = "";
    var timestamp = "";

    var project_name = '';
    var userArray = [];
    //选中的负责人
    var principal = '';
    var selectPrincipal = '';
    var followers = "";
    var followersIdArray = [];
    var selectFollowersIdArray = [];
    var selectType = ''; //0选择负责人   1选择关注人

    //从任务页面进入，返回相应子页面（我负责的，我关注的，我发起的）
    var taskBackType = $.getUrlParam('backType');
    if (taskBackType == undefined){
        taskBackType = 0;
    }

    $(function () {
        defaultProjectId(user_id);

        //限制字数
        $(".taskName").bind("input propertychange",function(){
            var nameStr = $(this).val();
            if(nameStr.length >= 40){
                $(".project-alert").text("任务名最多40字").show().fadeOut(2000);
            }
        });

        //返回方法
        //选择项目方法
        $("#selectProjectLi").click(
            function() {
                projectLists(user_id);
            }
        )

        $(document).on("click","#newTask-left",function(){
            window.location.href = "../../index.html?htmlType=0&taskListBack="+taskBackType;
        });

        $(document).on("click",".call_back",function(){
            $(".call_back").hide();
            $('.title_up').remove();
        });

        $(document).on("click","#newTaskSelectPrincipal",function(){
            //选择负责人
            //获取项目详情
            if (project_id.length<=0){
                $(".project-alert").text("请先选择项目").show().fadeOut(2000);
            }else{
                $("#addMemberNavigation-right").css('width', '20vw');
                $(".addMemberTitle").text("选择负责人");
                $("#addMemberDiv").show();
                $(".newTask-container").hide();
                $("#saveMember").text("");
                selectType = 0;
                selectPrincipal = principal;
                projectDetail(project_id);
            }

        });

        $(document).on("click","#newTaskSelectFolloewrs",function(){
            //选择关注人
            //获取项目详情
            if (project_id.length<=0){
                $(".project-alert").text("请先选择项目").show().fadeOut(2000);
            }else{
                $("#addMemberNavigation-right").css('width', 'auto');
                $(".addMemberTitle").text("选择关注人");
                $("#addMemberDiv").show();
                $(".newTask-container").hide();

                var string = '确认选中(' + followersIdArray.length + ')';
                $("#saveMember").text(string);
                selectType = 1;
                for(var a in followersIdArray){
                    selectFollowersIdArray.push(followersIdArray[a]);
                }
                projectDetail(project_id);
            }
        });

        $(document).on("click","#addMemberNavigation-left",function(){
            //返回
            $("#addMemberDiv").hide();
            $(".newTask-container").show();
            $(".member-li").remove();
            if (selectType == 0){
                selectPrincipal = '';
            }
            else {
                selectFollowersIdArray = [];
            }
        });

        $(document).on("click","#addMemberNavigation-right",function(){
            //选中负责人
            if (selectType == 0){
                return;
            }
            else {
                $("#addMemberDiv").hide();
                $(".newTask-container").show();
                $(".member-li").remove();
                followersIdArray = [];

                if (selectFollowersIdArray.length == 0) {
                    $("#attention").text("添加关注人");
                    return;
                }

                for (key in selectFollowersIdArray){
                    followersIdArray.push(selectFollowersIdArray[key]);
                }
                selectFollowersIdArray = [];
                for (key in userArray){
                    if (userArray[key].id == followersIdArray[0]){
                        if (followersIdArray.length == 1){
                            var string = userArray[key].name;
                            $("#attention").text(string);
                        }
                        else {
                            var string = userArray[key].name+'  等'+followersIdArray.length+"人关注";
                            $("#attention").text(string);
                        }
                    }
                }
            }
        });

        //保存按钮方法
        $("#saveNewTask").click(
            function(){
                var taskVal = HTMLEncode($(".taskName").val());
                var taskTitle = $.trim(taskVal);
                if ( taskTitle == ""){
                    $(".project-alert").text("任务标题不能为空").show().fadeOut(2000);
                }else if (project_id.length <= 0){
                    $(".project-alert").text("请选择项目").show().fadeOut(2000);
                }else if (principal.length <= 0){
                    $(".project-alert").text("请选择负责人").show().fadeOut(2000);
                }else{
                    var timeString = $(".newTask-input").val();
                    if (timeString == "设置截止时间") {
                        $(".project-alert").text("请设置截止时间").show().fadeOut(2000);
                    }
                    else {
                        var year = timeString.substr(0,4);
                        var mon = timeString.substr(5,2);
                        var day = timeString.substr(8,2);
                        var date = year+"-"+mon+"-"+day;
                        initTimestamp(date);
                        for (key in followersIdArray){
                            if (key == 0){
                                followers += followersIdArray[key];
                            }
                            else {
                                followers = followers+','+followersIdArray[key];
                            }
                        }
                        createProjectTask(project_id,taskTitle,user_id,principal,timestamp,followers);
                    }
                }
            }
        )

        //绑时间控件
        selectDate($(".newTask-input"));

    });

    //创建项目任务
    function createProjectTask(project_id,project_task_name,create_id,response_id,deadline,followers) {
        /*
         project_id 项目id
         project_task_name 项目任务名
         create_id 任务创建者id
         response_id 任务指派者id
         deadline 任务截止时间
         followers 任务观察者id字符串
         */

        var url = apiurl+"/projects/task";
        var urlData = {
            project_id:project_id,
            project_task_name:project_task_name,
            create_id:create_id,
            response_id:response_id,
            deadline:deadline,
            followers:followers,
            token:token,
            imtoken:imToken,
            qyxBindId:qyxBindId,
            title:user_name+"在"+project_name+"创建了一个任务"
        }
        var form =new FormData();
        form.append("project_id",project_id);
        form.append("project_task_name",project_task_name);
        form.append("create_id",create_id);
        form.append("response_id",response_id);
        form.append("deadline",deadline);
        form.append("followers",followers);
        form.append("token",token);
        form.append("imtoken",imToken);
        form.append("qyxBindId",qyxBindId);
        form.append("title",user_name+"在"+project_name+"创建了一个任务");
        $.ajax({
            url:url,
            type:"POST",
            data:form,
            "processData": false,
            "contentType": false,
            "mimeType": "multipart/form-data",
            beforeSend:function(){
                $(".change-p").text("正在创建任务");
                $(".change-alert").show();
            },
            complete:function(){
                $(".change-alert").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if (data.code == 0) {
                        $(".project-alert").text("创建任务成功").show().fadeOut(2000);
                        var project_task_id = data.data.project_task_id;
                        window.location.href = "taskDetail.html?id="+project_task_id+"&detailBack=0";
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //时间控件方法
    function selectDate(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = { preset: 'date' };
        opt.datetime = { preset: 'datetime' };
        opt.time = { preset: 'time' };
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            dateFormat: 'yyyy-mm-dd',
            startYear: currYear - 10, //开始年份
            endYear: currYear + 10, //结束年份
            minDate: new Date(),
            onSelect:function(){
                var timeString = $("#deadline").val();
                var year = timeString.substr(0,4);
                var mon = timeString.substr(5,2);
                var day = timeString.substr(8,2);
                var date = year+"年"+mon+"月"+day+"日 到期";
                $("#deadline").val(date);
            }
        };
        var optDateTime = $.extend(opt['datetime'], opt['default']);
        obj.mobiscroll(optDateTime).date(optDateTime);
    }

    //时间转换时间戳
    function initTimestamp(date){
        var time = date;
        time = new Date(Date.parse(new Date(date)));
        timestamp = time.getTime();
    }

    //获取项目详情
    function projectDetail(project_id) {
        var url = apiurl+"/projects/"+project_id+"";
        var urlData = {
            user_id:user_id,
            token:token
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            beforeSend:function(d){
                $(".memberloading").show();
            },
            complete:function(d){
                $(".memberloading").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var comData = d;
                    if (d.code == undefined) {
                        comData = JSON.parse(d);
                    }
                    if (comData.code == 0) {
                        var data = JSON.parse(d).data;
                        project_name = data.project_title;
                        userArray = data.userCallbackString;
                        for (key in userArray) {
                            var html = '';
                            var avatar = userArray[key].avatar;
                            var name = userArray[key].name;
                            var qyxBindId = userArray[key].qyxBindId;
                            var img_url;
                            //if (avatar == "") {
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(name) + "</div>"
                            //} else {
                            if (avatar.length > 0){
                                var src = avatar_getUrl(localStorage.user_id, localStorage.token, avatar);
                                img_url += "<img src='" + src + "' class='user_pic' hidden>";
                            }
                            if (selectType == 0) {
                                if (userArray[key].id == selectPrincipal) {
                                    //当前负责人
                                    html = '<li class="member-li" userId="' + userArray[key].id + '">' +
                                        '<div class="addDiv"></div> '+
                                        img_url +
                                        '<p class="nameP">' + userArray[key].name + '</p>' +
                                        '<div class="user_right"><img class="select_principal_img" src="../../../log/logImg/tick.png" /></div> '+
                                        '</li>'
                                }
                                else {
                                    html = '<li class="member-li" userId="' + userArray[key].id + '">' +
                                        '<div class="addDiv"></div> '+
                                        img_url +
                                        '<p class="nameP">' + userArray[key].name + '</p></li>'
                                }
                            }
                            else {
                                html = '<li class="member-li" userId="' + userArray[key].id + '" isSelect="0">' +
                                    '<img class="addImg" src="../../images/task/circleCheckBoxUnselect.png" />' +
                                    img_url +
                                    '<p class="nameP">' + userArray[key].name + '</p></li>'
                                for (i in selectFollowersIdArray) {
                                    if (userArray[key].id == selectFollowersIdArray[i]) {
                                        //当前关注人
                                        html = '<li class="member-li" userId="' + userArray[key].id + '" isSelect="1">' +
                                            '<img class="addImg" src="../../images/task/circleCheckBoxSelect.png" />' +
                                            img_url +
                                            '<p class="nameP">' + userArray[key].name + '</p></li>'
                                    }
                                }

                            }
                            $(".member-ul").append(html);
                        }

                        showAvatar(".user_pic");

                        $(".member-li").on("click",function(){
                            if (selectType == 0) {
                                //选择负责人
                                selectPrincipal = $(this).attr("userId");
                                principal = selectPrincipal;
                                selectPrincipal = '';
                                for (var key in userArray){
                                    if (userArray[key].id == principal){
                                        var string = userArray[key].name+'  负责';
                                        $("#principal").text(string);
                                    }
                                }
                                $("#addMemberDiv").hide();
                                $(".newTask-container").show();
                                $(".member-li").remove();
                            }
                            else {
                                return;
                            }
                        });

                        $(".addImg").on("click", function () {
                            if (selectType == 0) {
                                //选择负责人
                                return;
                            }
                            else {
                                //选择关注人
                                var selectUserId = $(this).parent().attr("userId");
                                var isSelect = $(this).parent().attr("isSelect");
                                if (isSelect == 0) {
                                    $(this).attr("src", "../../images/task/circleCheckBoxSelect.png");
                                    $(this).parent().attr("isSelect", "1");
                                    selectFollowersIdArray.push(selectUserId);
                                }
                                else {
                                    $(this).attr("src", "../../images/task/circleCheckBoxUnselect.png");
                                    $(this).parent().attr("isSelect", "0");
                                    for (key in selectFollowersIdArray) {
                                        if (selectFollowersIdArray[key] == selectUserId) {
                                            selectFollowersIdArray.splice(key, 1);
                                        }
                                    }
                                }

                                var string = '确认选中(' + selectFollowersIdArray.length + ')'
                                $("#saveMember").text(string);
                            }
                        });
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //获取项目列表
    function projectLists(user_id,type) {
        var url = apiurl+"/projects/list";
        var urlData = {
            user_id:user_id,
            group_id:group_id
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            beforeSend:function(){
                $(".change-p").text("正在获取项目列表");
                $(".change-alert").show();
            },
            complete:function(){
                $(".change-alert").hide();
            },
            success:function(d){
                var comData = d;
                if (d.code == undefined) {
                    comData = JSON.parse(d);
                }
                if (comData.code == 0){
                    var data = JSON.parse(d).data;
                    var divHeight = data.length * 7.8125;
                    var padTop = (100 - divHeight)/2;
                    if (padTop < 20){
                        padTop = 20;
                    }
                    $(".call_back").css("paddingTop",padTop+"vh");

                    for(var i=0;i<data.length;i++){
                        var title = data[i].project_title;
                        var projectId = data[i].project_id;
                        var html = '';
                        if (project_id == projectId){
                            //当前所选项目
                            var html = '<div class="title_up" projectId="'+projectId+'" projectName="'+title+'">'+
                                '<div class="le">'+title+'</div>'+
                                '<div class="ri">'+
                                '<img class="createNewProjectImg" src="../../../questionnaire/public/img/upper_limit_on.png"></div></div>'
                        }
                        else {
                            var html = '<div class="title_up" projectId="'+projectId+'" projectName="'+title+'">'+
                                '<div class="le">'+title+'</div>'+
                                '<div class="ri">'+
                                '<img class="createNewProjectImg" src="../../../questionnaire/public/img/upper_limit_off.png"></div></div>'
                        }

                        $(".content_big").prepend(html);
                    }

                    $(".call_back").show();

                    $('.title_up').click(function(){
                        project_id = $(this).attr("projectId");
                        var projectTitle = $(this).attr("projectName");
                        var img = $(this).find("img");
                        $('.ri img').attr('src','../../../questionnaire/public/img/upper_limit_off.png');
                        img.attr('src','../../../questionnaire/public/img/upper_limit_on.png');
                        $("#projectName").text(projectTitle);
                        $('.call_back').hide();
                        $('.title_up').remove();
                    });
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //获取默认项目ID
    function defaultProjectId(user_id) {
        var url = apiurl+"/projects/list";
        var urlData = {
            user_id:user_id,
            group_id:group_id
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            beforeSend:function(){
                $(".change-p").text("正在获取默认项目信息");
                $(".change-alert").show();
            },
            complete:function(){
                $(".change-alert").hide();
            },
            success:function(d){
                var comData = d;
                if (d.code == undefined) {
                    comData = JSON.parse(d);
                }
                if (comData.code == 0){
                    var data = JSON.parse(d).data;
                    for (var i = 0; i < data.length; i++){
                        if (data[i].project_title == '默认项目'){
                            if (project_id.length <= 0){
                                project_id = data[i].project_id;
                            }
                            else if (data[i].project_id < project_id){
                                project_id = data[i].project_id;
                            }
                        }
                    }
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }

})(jQuery);
